﻿const dw = require('./db-worker');
const SYS_PASSWORD = "NmOvkERXGg%8uqlfpTx,o6u:l5+b0#`^&aN&xPhvfi&W*@g>|6g}D%#&75ni.t";
const SYS_NAME = 'HumanSMS';

async function testEnoAndEchoJson(req, res, fn) {
    var eno = req.session && req.session.uid;
    if (eno) {
        var data = await fn(eno);
        //console.log(`data := ${JSON.stringify(data)}`);
        if (data) {
            res.json(data);
            return
        }
    }
    res.end();
}


module.exports = {

    async sysLoad(req, res) { await testEnoAndEchoJson(req, res, eno => dw.sysLoad(eno)) },

    async sendLoad(req, res) { await testEnoAndEchoJson(req, res, eno => dw.sendLoad(eno)) },

    async authorizeLoad(req, res) { await testEnoAndEchoJson(req, res, eno => dw.authorizeLoad(eno)) },

    async updatePerm(req, res) {
        await testEnoAndEchoJson(req, res, async eno => {
            var { identity, perm } = req.params;
            if (!identity || perm === undefined) {
                console.error(`update perm with bad parameters : grantor:${eno} identity:${identity} perm:${perm}`);
            } else {
                await dw.updatePermission(eno, req.ip, identity, perm);
            }
        })
    },

    async loadStat(req, res) { await testEnoAndEchoJson(req, res, eno => dw.getStatistics(eno)) },

    async loadHistory(req, res) {
        var eno = req.session && req.session.uid;
        if (!eno) {
            res.end();
            return
        }

        var counts = await dw.historyGetCount(eno);
        var sent = { ...(await dw.historyLoadSent(eno))[0], title: '消息发送记录' };
        var receipt = { ...(await dw.historyLoadRece(eno))[0], title: '消息接收记录' };

        res.json({ counts, sent, receipt })
    },

    async loadHistoryPage(req, res) {
        await testEnoAndEchoJson(req, res, async eno => {
            var { category, pageIndex = 0 } = req.params;
            if (!category || category !== 'sent' && category !== 'rece') {
                res.end();
                return
            }

            var result = await (category === 'sent' ? dw.historyLoadSent : dw.historyLoadRece)(eno, pageIndex);
            var [{ rowset }] = result;
            return rowset;
        })
    },

    end(req, res) {
        req.session.destroy();
        res.end();
    }
}